<?php
/**
 * 创建email的xml
 * 
 * modifiedOn 2010-10-25 oushunbao
 * 		增加可以附带附件 BuildEmailWithAttachments
 *
 *
 * 多用于批量生成
 */
require_once("emailFormat.php");

class BatchBuildXMLEmail{
	var $fromEmail = '';
	var $fromName = '';
	var $emailListId = '';
	var $xmlDir = '';
	var $xmlPre = '';
	
	function BatchBuildXMLEmail($options = array()) {
		// default
		$this->xmlDir = '/tmp/sending/';
		$this->xmlPre = 'note';
		$this->initialParams($options);
	}
	// 初始化变量
	public function initialParams($options){
		$keys = array('fromEmail', 'fromName', 'emailListId', 'xmlPre', 'xmlDir');	
		foreach ($keys as $key){
			if (isset($options[$key])) $this->$key = $options[$key];
		}
	}
	
	/**
	 * 对外接口：创建xml格式的邮件
	 *
	 * @param array $toInfoArray
	 * @param string $emailSubject
	 * @param string $emailContent
	 * @return errorMessage  (Attention 以前返回 true / false)
	 */
	public function buildXMLEmail($toInfoArray,$emailSubject,$emailContent){
		return $this->buildXMLEmailWithAttachments($toInfoArray,$emailSubject,$emailContent, array());
	}
	/**
	 * 对外接口：创建xml格式的邮件, 并且可以发送附件
	 * 附件中的fullOriFileName 最好是绝对路径，
	 * 系统将复制这些文件到 $xmlDir/{$xmlfilename}_attaches/下, 并且文件更名为attachName
	 *
	 * @param array $toInfoArray
	 * @param string $emailSubject
	 * @param string $emailContent
	 * @param array $emailAttachments array(attachName1 => fullOriFileName1, ...)
	 * @return errorMessage 
	 */
	public function buildXMLEmailWithAttachments($toInfoArray,$emailSubject,$emailContent, $emailAttachments){
		$xmlDir = $this->xmlDir;
		$xmlPre = $this->xmlPre;
		
		$xmlFileName = $this->getFullFileNameForXML($xmlDir, $xmlPre);
		$attachList = array();
		
		if (count($emailAttachments) > 0){
		
			$attachFullPath = $xmlFileName . '_attaches/';
			$attachPath = basename($xmlFileName) . '_attaches/';;
			$this->mkdir_p($attachFullPath);
			foreach ($emailAttachments as $attachName => $fullOriFileName){
				if (!file_exists($fullOriFileName)){
					return 'not find the file :' . $fullOriFileName;
				}
				copy($fullOriFileName, $attachFullPath . $attachName);
				array_push($attachList, $attachPath . $attachName);
			}
		}
	
		$xml = $this->CreateEmailXML($toInfoArray,$emailSubject,$emailContent, $attachList);	
		if (empty($xml)) {
			return 'not create the xml.';
		}
		
		file_put_contents($xmlFileName, $xml);
		return '';
	}
	
	/**
	 * 创建标准格式的xml，可用于发送给多个人或一个人
	 *
	 * @param array $toInfoArray 收件人列表 格式为 array(array('to_name' => 'tom','to_email' => 'tom@xxx.com'),...);
	 * @param string $emailSubject 邮件主题。
	 * @param string $emailContent 邮件内容。
	 * @return string 生成的xml字符串。
	 */
	private function CreateEmailXML($toInfoArray,$emailSubject,$emailContent, $attachList) {
		//查询参数
		if (empty($toInfoArray) || !is_array($toInfoArray) || empty($emailSubject) || empty($emailContent)) {
			return false;
		}
		if (!$this->CheckArrayStructure($toInfoArray)) {
			return false;
		}
				
		$emailFormatObj = new emailFormat($toInfoArray, $this->emailListId, $this->fromName, $this->fromEmail, 
				'', '', $emailSubject, $emailContent, $attachList);
		return $emailFormatObj->buildEmail();
		
	}
	
	
	// 获取存放xml所使用的文件名
	private function getFullFileNameForXML($xmlDir, $xmlPre=''){
		$randIndex = rand(1000, 9999);
		$this->mkdir_p($xmlDir);
		$now = date("YmdHis");
		$fileName = $xmlDir.$xmlPre.$now. '_' . $randIndex . '.xml';
		while (file_exists($fileName)){
			sleep(1);
			$now = date("YmdHis");
			$fileName = $xmlDir.$xmlPre.$now. '_' . $randIndex . '.xml';
		}		
		return $fileName;
	}
	
	/**
	 * 检查收件人列表数组是否合乎规格。
	 *
	 * @param array $toInfoArray 电子邮件收件人列表 规格应为 array(array('to_name' => 'tom','to_email' => 'tom@xxx.com'),array(...),...)，
	 * 其中每个收件人array中，to_name为必须。
	 * @return boolean 是否合乎规格。
	 */
	private function CheckArrayStructure($toInfoArray) {
		if (empty($toInfoArray)) {
			return false;
		}
		foreach ($toInfoArray as $item) {
			if (! $this->isEmail($item['to_email'])) return false;
		}
		return true;
	}
	
	// 建立目录
	private function mkdir_p($dirname){
	    if (!file_exists($dirname)){
	        $this->mkdir_p(dirname($dirname));
	        mkdir($dirname);
	    }
	}

	private function isEmail($email){
		$pattern="/^([\w\.-]+)@([a-zA-Z0-9-]+)(\.[a-zA-Z\.]+)$/i";//包含字母、数字、下划线_和点.的名字的email
		if(preg_match($pattern,$email,$matches)){
			return true;
		}else{
			return false;
		}
	}
}
?>
